#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>

// 使⽤mmap分配内存
// MAP_PRIVATE | MAP_ANONYMOUS 不更改底层文件，且匿名无文件
void *my_malloc(size_t size)
{
    void *ptr = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (ptr == MAP_FAILED)
    {
        perror("mmap");
        exit(EXIT_FAILURE);
    }
    return ptr;
}
// 使⽤munmap释放内存
void my_free(void *ptr, size_t size)
{
    if (munmap(ptr, size) == -1)
    {
        perror("munmap");
        exit(EXIT_FAILURE);
    }
}

int main()
{
    size_t size = 1024; // 分配1KB内存
    char *ptr = (char *)my_malloc(size);
    // 使⽤分配的内存（这⾥只是简单地打印指针值）
    printf("Allocated memory at address: %p\n", ptr);
    // ... 在这⾥可以使⽤ptr指向的内存 ...
    memset(ptr, 'A', size);
    for (int i = 0; i < size; i++)
    {
        printf("%c ", ptr[i]);
        fflush(stdout);
        sleep(1);
    }
    // 释放分配的内存
    my_free(ptr, size);
    return 0;
}

//mmap查看匿名虚拟分配内存，info proc mapping
// (gdb) p ptr
//     $1 = 0x555555555140 <_start> "\363\017\036\372\061\355I\211\321^H\211\342H\203\344\360PTE1\300\061\311H\215=x\001"
//     0x7ffff7fef000     0x7ffff7ffa000     0xb000    0x2c000  r--p   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
//     0x7ffff7ffb000     0x7ffff7ffd000     0x2000    0x37000  r--p   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
//     0x7ffff7ffd000     0x7ffff7fff000     0x2000    0x39000  rw-p   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
//     0x7ffffffde000     0x7ffffffff000    0x21000        0x0  rw-p   [stack]
//     0xffffffffff600000 0xffffffffff601000     0x1000        0x0  --xp   [vsyscall]
//     (gdb) n
//     34	    printf("Allocated memory at address: %p\n", ptr);
//     (gdb) p ptr
//     $2 = 0x7ffff7ffa000 ""
//     (gdb) info proc mapping


// 0x7ffff7ffa000     0x7ffff7ffb000     0x1000        0x0  rw-p   
//       0x7ffff7ffb000     0x7ffff7ffd000     0x2000    0x37000  r--p   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
//       0x7ffff7ffd000     0x7ffff7fff000     0x2000    0x39000  rw-p   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
//       0x7ffffffde000     0x7ffffffff000    0x21000        0x0  rw-p   [stack]
//   0xffffffffff600000 0xffffffffff601000     0x1000        0x0  --xp   [vsyscall]




